﻿using System;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;

namespace Chapter15
{
    //以熟悉的方式处理异步的异常
    [Description("Listing 15.04")]
    class WrappedExceptions
    {
        static void Main()
        {
            MainAsync().Wait();
        }

        static async Task MainAsync()
        {
            //开始异步读取
            Task<string> task = ReadFileAsync("garbage file");
            try
            {
                //等待内容
                string text = await task;
                Console.WriteLine("File contents: {0}", text);
            }
            catch (IOException e)//处理IO失败
            {
                Console.WriteLine("Caught IOException: {0}", e.Message);
            }
        }

        static async Task<string> ReadFileAsync(string filename)
        {
            //同步打开文件
            using (var reader = File.OpenText(filename))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}
